package zhongbo.java.air.dictionary.service.Impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zhongbo.java.air.common.exception.BusinessException;
import zhongbo.java.air.common.exception.ExceptionCode;
import zhongbo.java.air.common.vo.PageVo;
import zhongbo.java.air.dictionary.mapper.AirPortMapper;
import zhongbo.java.air.dictionary.model.AirPort;
import zhongbo.java.air.dictionary.model.enums.Change;
import zhongbo.java.air.dictionary.service.IAirPortService;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class IAirPortServiceImpl implements IAirPortService {

    @Autowired
    AirPortMapper airPortMapper;
    @Override
    public AirPort insert(AirPort airPort) {
        //ICAO机场代码，iataCodeIATA代码，机场全称，时区不能有一个为空
        if(StrUtil.isBlank(airPort.getIcaoCode()) ||
           StrUtil.isBlank(airPort.getIataCode()) ||
            StrUtil.isBlank(airPort.getName()) ||
            StrUtil.isBlank(airPort.getTimezone())){
            throw new RuntimeException("机场必填信息不能为空");
        }
        //纬度（WGS84坐标系，小数点后6位）或经度（WGS84坐标系，小数点后6位）等于空
        if(airPort.getLatitude()==null || airPort.getLongitude()==null){
            throw new RuntimeException("纬度或经度不能等于空");
        }

        //（枚举值：OPERATIONAL-运行中, CLOSED-已关闭, RESTRICTED-限制运行
        if(!Arrays.asList(Change.CLOSED,Change.OPERATIONAL,Change.RESTRICTED).contains(airPort.getStatus())){
            throw new RuntimeException("枚举类型不符合要求,请选择：CLOSED(已关闭),OPERATIONAL(运行中),RESTRICTED(限制运行)");
        }

        //ICAO机场代码（如 ZBAA）严格字符限制==4
        if(airPort.getIcaoCode().length()!=4){
            throw new RuntimeException("ICAO机场代码字符长度不等于4");
        }
        //IATA代码（如 PEK）严格字符限制==3
        if(airPort.getIataCode().length()!=3){
           throw new RuntimeException("IAIA代码字符长度不等于3");
        }

      //获得纬度
        Double latitude = airPort.getLatitude();
        String Latitudes =String.format("%.6f",latitude);//双精度转字符串，确保有六位数
        //正则表达式--^匹配字符串开始-?匹配可选的负号[1-8]?[1-9]匹配组合0-89的数字|90或精确匹配90-\\.匹配小数点-\\d{6}匹配6个小数点$字符串结束
        String regex ="^-?([1-8]?[1-9]|90)\\.\\d{6}$";
        //pattern是正则表达类
        Pattern pattern =Pattern.compile(regex);
        //输入字符串匹配正则表达式的类--matcher创建Matcher类
        Matcher matcher = pattern.matcher(Latitudes);
         //matches格式正确返回true
        if(!matcher.matches()){
            throw new RuntimeException("纬度格式不符合要求,纬度范围-90.000000到90.000000");
        }
        //获得经度
        Double longitude=airPort.getLongitude();
        String Longitudes =String.format("%.6f",longitude);//双精度浮点数转字符串
         //正则表达式
        String reges="^-?([1]?[1-7]?[1-9]|180)\\.\\d{6}$";
        Pattern pattern1 =Pattern.compile(reges);
        Matcher matcher1 = pattern1.matcher(Longitudes);
        if(!matcher1.matches()){//纬度格式
            throw new RuntimeException("经度格式不对,范围属于-180.000000到180.000000");
        }

        //查询记录是否存在，icaoCode并且iataCode唯一--不能重复--selectone则查询得到全部记录
        QueryWrapper<AirPort> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("icao_code",airPort.getIcaoCode());
        queryWrapper.or().eq("iata_code",airPort.getIataCode());
        boolean exist =airPortMapper.exists(queryWrapper);
        //存在true
        if(exist){
            throw new IllegalArgumentException("机场代码，IATA代码重复，重新输入");
        }
        int add = airPortMapper.insert(airPort);
        if(add>0){
            return airPort;
        }
        throw new RuntimeException("机场信息添加失败");

    }

    @Override
    public String delete(String id) {
        AirPort airPort =airPortMapper.selectById(id);
        if(airPort==null){
            throw new BusinessException(ExceptionCode.ERROR);
        }

        airPortMapper.deleteById(id);
        return id;
    }

    @Override
    public AirPort select(String id) {
        AirPort airPort =airPortMapper.selectById(id);
        return airPort;
    }


    @Override
    public AirPort updateStatus(AirPort airPort) {
        //查id
        AirPort select =airPortMapper.selectById(airPort.getId());
        if(select==null){
            throw new RuntimeException("该航迹信息不存在");
        }
        //枚举
        if(!(airPort.getStatus().equals(Change.CLOSED) ||airPort.equals(Change.OPERATIONAL) ||airPort.equals(Change.RESTRICTED))){
            throw new RuntimeException("状态输入不符合格式");
        }


        int exit =airPortMapper.updateById(airPort);

        if(exit>0){
            return airPort;
        }

        return null;
    }

    @Override
    public PageVo<AirPort> findPage(String id, Integer page, Integer pageSize) {
        QueryWrapper<AirPort> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(id)) {
            queryWrapper.like("id", id);
        }
        IPage<AirPort> pageParam = new Page<>(page, pageSize);
        IPage<AirPort> airPortIPage = airPortMapper.selectPage(pageParam, queryWrapper);
        return new PageVo<>(airPortIPage);
    }
}
